﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;
using SportsStore.WebUI.Models;

namespace SportsStore.WebUI.Controllers
{
    /// <summary>
    /// This is the controller to show/manipulate products in SportsStore.
    /// </summary>
    public class ProductController : Controller
    {
        public int pageSize = 4;
        private readonly IProductRepository _productRepository;

        public ProductController(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        public ViewResult List(string category, int page = 1)
        {
            var totalProducts = _productRepository.Products.ToList();
            var itemsToShow = totalProducts
                .Where(prod => category == null || prod.Category.Equals(category))
                .OrderBy(p => p.ProductID)
                .Skip((page - 1) * pageSize)
                .Take(pageSize);

            var pagingInfo = new PagingInfo()
            {
                CurrentPage = page,
                ItemsPerPage = pageSize,
                TotalItems = category == null ? totalProducts.Count : totalProducts.Where(prod => prod.Category.Equals(category)).Count()
            };

            return View(new ProductListViewModel() { PagingInfo = pagingInfo, Products = itemsToShow, CurrentCategory = category });
        }

        public FileContentResult GetImage(int productId)
        {
            var prod = _productRepository.Products
                .Where(p => p.ProductID == productId)
                .FirstOrDefault();

            if (prod != null)
            {
                return File(prod.ImageData, prod.ImageMimeType);
            }

            return null;
        }
    }
}
